package org.xshop.service.impl;

import java.math.BigDecimal;
import java.util.Map;

import org.springframework.cache.annotation.CacheConfig;
import org.xshop.mapper.TMemberAddressMapper;
import org.xshop.model.TMemberAddress;
import org.xshop.service.ITMemberAddressService;

import com.weibo.api.motan.config.springsupport.annotation.MotanService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.support.Pagination;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.GaodeMapUtil;
import top.ibase4j.core.util.InstanceUtil;

/**
 * <p>
 * 收货地址 服务实现类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2018-03-01
 */
@MotanService(interfaceClass = ITMemberAddressService.class)
@CacheConfig(cacheNames = "TMemberAddress")
public class MemberAddressService extends BaseServiceImpl<TMemberAddress, TMemberAddressMapper>
implements ITMemberAddressService {

    @Override
    public Object updateAddress(TMemberAddress param) {
        Integer isDefault = param.getIsDefault();
        // 默认地址
        if (DataUtil.isNotEmpty(isDefault) && isDefault.intValue() == 1) {
            // 清空其他默认地址
            Map<String, Object> params = InstanceUtil.newHashMap();
            params.put("memberId", param.getMemberId());
            Pagination<TMemberAddress> page = query(params);
            if (page != null) {
                for (TMemberAddress address : page.getRecords()) {
                    if (address.getIsDefault().intValue() == 1 && !address.getId().equals(param.getId())) {
                        address.setIsDefault(0);
                        update(address);
                    }
                }
            }
        }
        try {
            Map<String, Object> locas = GaodeMapUtil.getCoordinateByAddress(param.getAddressDetail(),
                param.getAddressCity());
            param.setLon(new BigDecimal(locas.get("xIndex").toString()));
            param.setLat(new BigDecimal(locas.get("yIndex").toString()));
        } catch (Exception e) {
            logger.error("", e);
        }
        return update(param);
    }

}